/*
 * CS_ENTER_EVENT_DUNGEON.cpp
 *
 *  Created on: 2013. 8. 28.
 *      Author: mega@gamevil.com
 */

#include "../../User.h"
#include "../../NResource/Static.h"
#include "../../NLogic/Space.h"
#include "../../NLogic/Stamina.h"
#include "dungeon.h"

namespace ProjectZ { namespace NCommand { namespace NDungeon {

void CS_ENTER_EVENT_DUNGEON::OnExecute(User * pUser, ::Network::Packet * pPacket)
{
	PREPARE_PACKET;

	char decreaseStamina = 0;

	*pPacket >> decreaseStamina;

	if (0 >= decreaseStamina)
	{
		DEBUGLOG("%s : INVALID decreaseStamina=%d", decreaseStamina);
		SendPacket(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	NLogic::Space * pWorld = pUser->GetSpace();
	if (NULL == pWorld)
	{
		DEBUGLOG("%s : NULL == pWorld", __FUNCTION__);
		SendPacket(pUser, ACK_NO_SPACE);
		return;
	}

	// 던전 다시하기, Changed by spencer(2014.07.04)
	// 던전 다시하기 기능으로 인해서 던전 오픈은 world|dungeon 모두에서 가능하다.
	/*
	if (pWorld->GetData()._spaceType != NLogic::Space::SpaceType::WORLD)
	{
		DEBUGLOG("%s : User Space is Not WORLD", __FUNCTION__);
		SendPacket(pUser, ACK_NO_SPACE);
		return;
	}

	if (pUser->GetEnumState() != User::EnumState::__NONE__)
	{
		DEBUGLOG("%s : User Status is Not Normal", __FUNCTION__);
		SendPacket(pUser, ACK_UNKNOWN_ERROR);
		return;
	}
	*/

	if (false == NResource::Static::InstancePtr()->GetEventTime()->IsOpenEventDungeon(pUser))
	{
		SendPacket(pUser, ACK_NOT_EVENT_DUNGEON);
		return;
	}

	NLogic::Stamina * pStamina = pUser->GetStamina();
	if (NULL == pStamina)
	{
		DEBUGLOG("%s : pStamina is NULL", __FUNCTION__);
		SendPacket(pUser, ACK_UNKNOWN_ERROR);
		return;
	}


/*	time_t currentSec;
	time(&currentSec);


	// 현재 스태미너가 최대라면 남은 회복 시간을 현재시간으로 설정
	if (pUser->GetCharacterInfo().event_stamina == EVENT_DUNGEON_STAMINA_MAX)
		pUser->GetCharacterInfo().recover_stamina_sec = currentSec;

	DEBUGLOG("CS_ENTER_EVENT_DUNGEON : user_seq=%d, slot_seq=%d, cur_stamina=%d, decrease_stamina=%d",
			pUser->GetUserSeq(), pUser->GetCharacterInfo().characterseq, pUser->GetCharacterInfo().event_stamina, decreaseStamina);

	int staminaGap = pUser->GetCharacterInfo().event_stamina - decreaseStamina;

	// 보유 스태미너가 부족한 경우
	if (staminaGap < 0)
	{
		SendPacket(pUser, ACK_NOT_ENOUGHT_STAMINA);
		return;
	}

	// 유저의 보유 스태미너 차감
	pUser->GetCharacterInfo().event_stamina -= decreaseStamina;*/

	if (true == pStamina->IsKeyLack(decreaseStamina))
	{
		SendPacket(pUser, ACK_NOT_ENOUGHT_STAMINA);
		return;
	}

	// 스태미너 차감
	if (false == pStamina->DecreaseKey(decreaseStamina))
	{
		SendPacket(pUser, ACK_NOT_ENOUGHT_STAMINA);
		return;
	}

	SendPacket(pUser, ACK_OK);

	// 열쇠 소모 연출중에 초대를 받는 것을 막기 위해 상태 변경
	pUser->SetEnumState(User::EnumState::ENTER_EVENT_DUNGEON);
}

void CS_ENTER_EVENT_DUNGEON::SendPacket(User * pUser, int16_t res)
{
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();

	*pAck << res;

	pAck->MakePacket(CMD_SC_ENTER_EVENT_DUNGEON);

	pUser->Send(pAck);
}

} /*NDungeon*/ } /*NCommand*/ } /*ProjectZ*/
